//
//  EqualViewController.m
//
//  Created by 周成龙
//

#import "EqualViewController.h"

@interface EqualPerson : NSObject

@property (nonatomic, copy)NSString *firstName;
@property (nonatomic, copy)NSString *lastName;
@property (nonatomic) NSUInteger age;

@end

@implementation EqualPerson

// NSObject
// - (BOOL)isEqual:(id)object;
// @property (readonly) NSUInteger hash;
- (BOOL)isEqual:(id)object {
    
    if ([self class] != [object class]) {
        return [super isEqual:object];
    }else {
        return [self isEqToPerson:(EqualPerson *)object];
    }
}

- (BOOL)isEqToPerson:(EqualPerson *)object {
    if (self == object) return YES;
    
    EqualPerson *p = (EqualPerson *)object;
    if (![_firstName isEqualToString:p.firstName]) {
        return NO;
    }
    if (![_lastName isEqualToString:p.lastName]) {
        return NO;
    }
    if (_age != p.age) {
        return NO;
    }
    
    return YES;
}

- (NSUInteger)hash {
    NSUInteger fnHash = [_firstName hash];
    NSUInteger lnHash = [_lastName hash];
    NSUInteger age = _age;
    return fnHash ^ lnHash ^ age;
}

@end







@interface EqualViewController ()

@end

@implementation EqualViewController
#pragma mark - LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self test1];
    [self test2];
    [self test3];
}

- (void)test1 {
    NSString *foo = @"Badger 123";
    NSString *bar = [NSString stringWithFormat:@"Badger %i", 123];
    
    BOOL equalA = (foo == bar);
    BOOL equalB = [foo isEqual:bar];
    BOOL equalC = [foo isEqualToString:bar];
    
    NSLog(@"equalA:%zd, equalB:%zd, equalC:%zd", equalA, equalB, equalC);
}

- (void)test2 {
    EqualPerson *p1 = [EqualPerson new];
    p1.firstName = @"zhang";
    p1.lastName = @"ming";
    p1.age = 18;
    
    EqualPerson *p2 = [EqualPerson new];
    p2.firstName = @"zhang1";
    p2.lastName = @"ming1";
    p2.age = 20;
    
    EqualPerson *p3 = [EqualPerson new];
    p3.firstName = @"zhang";
    p3.lastName = @"ming";
    p3.age = 18;
    
    BOOL equalA = [p1 isEqual:p2];
    BOOL equalB = [p1 isEqual:p3];
    BOOL equalC = (p1 == p2);
    BOOL equalD = (p1 == p3);
    BOOL equalE = (p1.hash == p2.hash);
    BOOL equalF = (p1.hash == p3.hash);
    
    NSLog(@"equalA: %i, equalB: %i", equalA, equalB);
    NSLog(@"equalC: %i, equalD: %i", equalC, equalD);
    NSLog(@"equalE: %i, equalF: %i", equalE, equalF);
}

- (void)test3 {
    NSMutableSet *set = [NSMutableSet set];
    
    NSMutableArray *arrayA = [@[@1, @2] mutableCopy];
    [set addObject:arrayA];
//    NSLog(@"set:%@", set);
    
    NSMutableArray *arrayB = [@[@1, @2] mutableCopy];
    [set addObject:arrayB];
//    NSLog(@"set:%@", set);
    
    NSMutableArray *arrayC = [@[@1] mutableCopy];
    [set addObject:arrayC];
//    NSLog(@"set:%@", set);
    
    [arrayC addObject:@2];
    NSLog(@"set:%@", set);
    
    NSLog(@"copySet:%@", [set copy]);
}

@end
